import axios from "../../http/axios.js";
import {
  apiUpdatePhone,
  apiGetWorerInformation
} from "../../http/server.js";
import {
  regExpPhone
} from "../../utils/regular.js";
Page({
  data: {
    titleOne: {
      key: "更改手机号码",
      value: "请输入新的手机号码"
    },
    titleTwo: {
      key: "+86",
      value: "13935311111"
    }
  },

  onLoad: function(options) {
    let userInfo = wx.getStorageSync("userInfo");
    let titleTwo = this.data.titleTwo;
    titleTwo.value = userInfo.phone || "";
    this.setData({
      titleTwo
    })
  },

  onReady: function() {

  },

  onShow: function() {

  },
  // 修改手机号
  updateInputValue: function(e) {
    let titleTwo = this.data.titleTwo;
    titleTwo.value = e.detail;
    this.setData({
      titleTwo
    })
  },
  //进行手机号验证
  checkPhone: function() {
    let phone = this.data.titleTwo.value;
    if (!phone.length) {
      wx.showToast({
        title: "请输入手机号",
        icon: "none"
      });
      return false;
    }
    if (!regExpPhone.test(phone)) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: "none"
      });
      return false;
    }
    return true;
  },
  //点击完成
  handleClickSuccess: function() {
    if (!this.checkPhone()) {
      return;
    }
    let userInfo = wx.getStorageSync("userInfo");
    // 修改手机号
    axios({
        url: apiUpdatePhone,
        method: "POST",
        data: {
          workersId: userInfo.workersId,
          phone: this.data.titleTwo.value
        }
      })
      .then(res => {
        if (res === undefined) {
          // 重新获取职工信息
          axios({
            url: apiGetWorerInformation,
            data: {
              workersId: userInfo.workersId
            }
          }).then(res => {
            wx.setStorageSync("userInfo", res);
            wx.showToast({
              title: "手机号修改成功",
              icon: "none"
            });
            setTimeout(() => {
              wx.navigateBack()
            }, 1500)
          })
        }
      })
  }
})